<template>
  <div class="order-container">
    <div class="order-header">
      <h1 class="order-title">我的订单</h1>
    </div>
    <div class="order-content">
      <el-tabs v-model="activeTab" class="order-tabs">
        <!-- 购买订单 -->
        <el-tab-pane label="购买订单" name="buy">
          <div class="order-list" v-loading="buyOrdersLoading">
            <template v-if="!buyOrders.length">
              <el-empty description="暂无购买订单"></el-empty>
            </template>
            <template v-else>
              <el-card v-for="order in buyOrders" :key="order.orderId" class="order-card">
                <div class="order-item">
                  <div class="order-product">
                    <img :src="getProductImage(order.product)" class="product-image" />
                    <div class="product-info">
                      <h3>{{ order.product?.title }}</h3>
                      <p class="price">¥{{ order.product?.price }}</p>
                    </div>
                  </div>
                  <div class="order-status">
                    <span class="status-tag" :class="getStatusClass(order.status)">{{ order.status }}</span>
                  </div>
                  <div class="order-actions">
                    <template v-if="order.status !== '已完成'">
                      <el-button 
                        type="primary" 
                        size="small"
                        @click="handleOrderAction(order)"
                      >
                        {{ getActionButtonText(order.status) }}
                      </el-button>
                    </template>
                    <el-button
                      type="info"
                      size="small"
                      @click="openOrderDetailDialog(order)"
                    >查看详细</el-button>
                  </div>
                </div>
              </el-card>
            </template>
          </div>
        </el-tab-pane>

        <!-- 销售订单 -->
        <el-tab-pane label="销售订单" name="sell">
          <div class="order-list" v-loading="sellOrdersLoading">
            <template v-if="!sellOrders.length">
              <el-empty description="暂无销售订单"></el-empty>
            </template>
            <template v-else>
              <el-card v-for="order in sellOrders" :key="order.orderId" class="order-card">
                <div class="order-item">
                  <div class="order-product">
                    <img :src="getProductImage(order.product)" class="product-image" />
                    <div class="product-info">
                      <h3>{{ order.product?.title }}</h3>
                      <p class="price">¥{{ order.product?.price }}</p>
                    </div>
                  </div>
                  <div class="order-status">
                    <span class="status-tag" :class="getStatusClass(order.status)">{{ order.status }}</span>
                  </div>
                  <div class="order-actions">
                    <template v-if="order.status !== '已完成'">
                      <el-button 
                        type="primary" 
                        size="small"
                        @click="handleOrderAction(order)"
                      >
                        {{ getActionButtonText(order.status) }}
                      </el-button>
                    </template>
                    <el-button
                      type="info"
                      size="small"
                      @click="openOrderDetailDialog(order)"
                    >查看详细</el-button>
                  </div>
                </div>
              </el-card>
            </template>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
      title="订单详情"
      :visible.sync="orderDetailDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <div v-if="currentOrderDetail">
        <div v-for="(value, key) in filteredOrderDetail(currentOrderDetail)" :key="key" style="margin-bottom: 12px;">
          <span style="font-weight:bold;">{{ getOrderFieldLabel(key) }}：</span>
          <span>{{ key.toLowerCase().includes('time') ? formatOrderTime(value) : value }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="orderDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import OrderService from '@/Services/OrderService'
import ProductService from '@/Services/ProductService'
import { parseJwt } from '@/utils/auth'
import UserService from '@/Services/UserService'
import LogService from '@/Services/LogService'
import MessageService from '@/Services/MessageService'

export default {
  name: 'OrderView',
  data() {
    return {
      activeTab: 'buy',
      buyOrders: [],
      sellOrders: [],
      buyOrdersLoading: false,
      sellOrdersLoading: false,
      orderDetailDialogVisible: false,
      currentOrderDetail: null
    }
  },
  created() {
    // 检查是否登录
    if (!localStorage.getItem('isLogged')) {
      this.$message.warning('请先登录')
      this.$router.push('/login')
      return
    }
    this.fetchOrders()
  },
  methods: {
    getCurrentUserId() {
      const token = localStorage.getItem('token')
      const decoded = parseJwt(token)
      return decoded && (
        decoded.userId ||
        decoded.id ||
        decoded.nameid ||
        decoded.sub ||
        decoded["http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"]
      )
    },
    async fetchOrders() {
      const userId = this.getCurrentUserId()
      if (!userId) return

      // 获取购买订单
      this.buyOrdersLoading = true
      try {
        const response = await OrderService.GetUserOrders(userId)
        if (response && response.code === 200 && response.data) {
          const orders = Array.isArray(response.data) ? response.data : response.data.$values || []
          // 获取每个订单的商品信息
          const ordersWithProducts = await Promise.all(
            orders.map(async (order) => {
              try {
                const productResponse = await ProductService.GetById(order.productId)
                if (productResponse && productResponse.code === 200 && productResponse.data) {
                  return {
                    ...order,
                    product: productResponse.data
                  }
                }
                return order
              } catch (error) {
                console.error(`获取商品信息失败 (ID: ${order.productId}):`, error)
                return order
              }
            })
          )
          this.buyOrders = ordersWithProducts
        }
      } catch (error) {
        this.$message.error('获取购买订单失败')
      } finally {
        this.buyOrdersLoading = false
      }

      // 获取销售订单
      this.sellOrdersLoading = true
      try {
        // 1. 获取当前用户发布的所有商品
        const productsRes = await ProductService.GetByUserId(userId)
        const products = productsRes.data?.$values || []
        // 2. 过滤掉状态为'在售'和'已下架'的商品
        const filteredProducts = products.filter(p => p.status !== '在售' && p.status !== '已下架')
        let allOrders = []
        // 3. 遍历这些商品，查找订单
        for (const product of filteredProducts) {
          const ordersRes = await OrderService.GetByProductId(product.productId)
          const orders = ordersRes.data?.$values || []
          // 4. 给每个订单加上商品信息
          orders.forEach(order => order.product = product)
          allOrders = allOrders.concat(orders)
        }
        this.sellOrders = allOrders
      } catch (error) {
        this.$message.error('获取销售订单失败')
      } finally {
        this.sellOrdersLoading = false
      }
    },
    getProductImage(product) {
      if (!product) return 'https://picsum.photos/300/200?random=' + Math.random()
      
      // 如果商品有base64图片数据，直接使用
      if (product.imageBase64) {
        return `data:image/jpeg;base64,${product.imageBase64}`
      }
      
      // 如果商品有图片路径，尝试获取本地图片
      if (product.imagePath) {
        const match = product.imagePath.match(/(\d+)\.jpg/)
        if (match) {
          const fileName = match[0] // 例如：10029.jpg
          const avatarList = require.context('@/assets/Aatar', false, /\.jpg$/).keys()
          const localPath = avatarList.find(path => path.includes(fileName))
          if (localPath) {
            return require(`@/assets/Aatar${localPath}`)
          }
        }
      }
      
      // 如果都没有，返回默认图片
      return 'https://picsum.photos/300/200?random=' + Math.random()
    },
    getStatusClass(status) {
      switch (status) {
        case '待付款':
          return 'status-pending'
        case '待发货':
          return 'status-shipping'
        case '待收货':
          return 'status-receiving'
        case '已完成':
          return 'status-completed'
        case '已取消':
          return 'status-cancelled'
        default:
          return ''
      }
    },
    getActionButtonText(status) {
      if (this.activeTab === 'sell' && status === '待发货') {
        return '发货'
      }
      if (this.activeTab === 'buy' && status === '待收货') {
        return '确认收货'
      }
      switch (status) {
        case '待付款':
          return '去支付'
        case '待发货':
          return this.activeTab === 'sell' ? '发货' : '提醒发货'
        case '已完成':
          return '查看详情'
        case '已取消':
          return '删除订单'
        default:
          return '查看详情'
      }
    },
    async handleOrderAction(order) {
      const userId = this.getCurrentUserId()
      let studentId = ''
      if (userId) {
        try {
          const userRes = await UserService.GetById(userId)
          if (userRes && userRes.data) {
            studentId = userRes.data.studentId || userRes.data.name || userRes.data.nickname || ''
          }
        } catch (e) { studentId = '' }
      }
      // 销售订单tab下，待发货状态，显示发货
      if (this.activeTab === 'sell' && order.status === '待发货') {
        try {
          await this.$confirm('确认发货吗？', '发货确认', {
            confirmButtonText: '确认发货',
            cancelButtonText: '取消',
            type: 'warning'
          })
          const response = await OrderService.UpdateStatus(order.orderId, '待收货')
          if (response && response.code === 200) {
            // 日志记录
            try {
              await LogService.Create({
                id: this.generateGuid(),
                userId: userId,
                detail: `${studentId}对${order.orderId}进行了发货`,
                createTime: new Date().toISOString()
              })
            } catch (logError) {
              console.error('记录订单操作日志失败：', logError)
            }
            // 发送消息给买家
            try {
              await MessageService.Create({
                userId: order.userId, // 买家id
                content: `您的订单${order.orderId}已发货，请注意查收。`
              })
            } catch (msgError) {
              console.error('发送发货消息失败：', msgError)
            }
            this.$message.success('发货成功！')
            await this.fetchOrders()
          } else {
            this.$message.error(response?.message || '发货失败')
          }
        } catch (error) {
          if (error === 'cancel') return
          this.$message.error(error?.response?.data?.message || '发货失败')
        }
        return
      }
      // 购买订单tab下，待收货状态，显示确认收货
      if (this.activeTab === 'buy' && order.status === '待收货') {
        try {
          await this.$confirm('确认已收到货物吗？', '确认收货', {
            confirmButtonText: '确认收货',
            cancelButtonText: '取消',
            type: 'warning'
          })
          const response = await OrderService.UpdateStatus(order.orderId, '已完成')
          if (response && response.code === 200) {
            // 日志记录
            try {
              await LogService.Create({
                id: this.generateGuid(),
                userId: userId,
                detail: `${studentId}对${order.orderId}进行了确认收货`,
                createTime: new Date().toISOString()
              })
            } catch (logError) {
              console.error('记录订单操作日志失败：', logError)
            }
            // 发送消息给卖家
            try {
              // 通过商品id查卖家id
              const productRes = await ProductService.GetById(order.productId)
              let sellerId = ''
              if (productRes && productRes.data) {
                sellerId = productRes.data.userId
              }
              if (sellerId) {
                await MessageService.Create({
                  userId: sellerId,
                  content: `买家已确认收货，订单${order.orderId}已完成。`
                })
              }
            } catch (msgError) {
              console.error('发送确认收货消息失败：', msgError)
            }
            this.$message.success('收货成功，订单已完成！')
            await this.fetchOrders()
          } else {
            this.$message.error(response?.message || '收货失败')
          }
        } catch (error) {
          if (error === 'cancel') return
          this.$message.error(error?.response?.data?.message || '收货失败')
        }
        return
      }
      // 其他逻辑保持不变...
      // 修复：只有在购买订单面板才允许支付操作
      if (this.activeTab !== 'buy') {
        this.$message.warning('只有买家可以进行支付操作')
        return
      }
      switch (order.status) {
        case '待付款':
          try {
            // 显示确认支付对话框
            await this.$confirm('确认支付该订单吗？', '支付确认', {
              confirmButtonText: '确认支付',
              cancelButtonText: '取消',
              type: 'warning'
            })
            // 调用更新订单状态的API
            const response = await OrderService.UpdateStatus(order.orderId, '待发货')
            if (response && response.code === 200) {
              // 日志记录
              try {
                await LogService.Create({
                  id: this.generateGuid(),
                  userId: userId,
                  detail: `${studentId}对${order.orderId}进行了支付`,
                  createTime: new Date().toISOString()
                })
              } catch (logError) {
                console.error('记录订单操作日志失败：', logError)
              }
              // 发送消息给卖家
              try {
                // 通过商品id查卖家id
                const productRes = await ProductService.GetById(order.productId)
                let sellerId = ''
                if (productRes && productRes.data) {
                  sellerId = productRes.data.userId
                }
                if (sellerId) {
                  await MessageService.Create({
                    userId: sellerId,
                    content: `买家已支付订单${order.orderId}，请尽快发货。`
                  })
                }
              } catch (msgError) {
                console.error('发送支付消息失败：', msgError)
              }
              this.$message.success('支付成功！')
              // 重新获取订单列表
              await this.fetchOrders()
            } else {
              this.$message.error(response?.message || '支付失败')
            }
          } catch (error) {
            if (error === 'cancel') {
              // 用户取消支付，不做处理
              return
            }
            console.error('支付失败:', error)
            this.$message.error(error?.response?.data?.message || '支付失败')
          }
          break
        case '待发货':
          // 提醒发货功能，买家提醒卖家
          try {
            // 通过商品id查卖家id
            const productRes = await ProductService.GetById(order.productId)
            let sellerId = ''
            if (productRes && productRes.data) {
              sellerId = productRes.data.userId
            }
            if (sellerId) {
              await MessageService.Create({
                userId: sellerId,
                content: `买家提醒您尽快发货，订单${order.orderId}。`
              })
              this.$message.success('已提醒卖家发货')
            }
          } catch (msgError) {
            console.error('提醒发货消息发送失败：', msgError)
            this.$message.error('提醒发货失败')
          }
          break
        case '待收货':
          this.$message.info('确认收货功能开发中')
          break
        case '已完成':
          this.$message.info('查看订单详情功能开发中')
          break
        case '已取消':
          this.$message.info('删除订单功能开发中')
          break
        default:
          this.$message.info('该状态暂不支持操作')
      }
    },
    // 生成GUID的方法
    generateGuid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
    },
    openOrderDetailDialog(order) {
      this.currentOrderDetail = order
      this.orderDetailDialogVisible = true
    },
    filteredOrderDetail(order) {
      // 仅展示$id、订单ID、商品ID、订单状态、创建时间
      const keys = ['$id', 'orderId', 'productId', 'status', 'createTime']
      const result = {}
      for (const key of keys) {
        if (order[key] !== undefined) {
          result[key] = order[key]
        }
      }
      return result
    },
    getOrderFieldLabel(key) {
      // 可根据实际字段名自定义中文
      const map = {
        orderId: '订单ID',
        productId: '商品ID',
        status: '订单状态',
        createTime: '创建时间',
        updateTime: '更新时间',
        price: '价格',
        product: '商品信息',
        // ...可扩展
      }
      return map[key] || key
    },
    formatOrderTime(val) {
      if (!val) return ''
      const d = new Date(val)
      const pad = n => n.toString().padStart(2, '0')
      return `${d.getFullYear()}年${pad(d.getMonth()+1)}月${pad(d.getDate())}日${pad(d.getHours())}小时${pad(d.getMinutes())}分${pad(d.getSeconds())}秒`
    },
  }
}
</script>

<style scoped>
.order-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.order-header {
  margin-bottom: 30px;
  text-align: center;
}

.order-title {
  font-size: 28px;
  color: #333;
  font-weight: 600;
  margin: 0;
  padding: 20px 0;
  border-bottom: 2px solid #ffe100;
}

.order-content {
  display: flex;
  justify-content: center;
}

.order-tabs {
  width: 100%;
  max-width: 1000px;
}

.order-list {
  margin-top: 20px;
}

.order-card {
  margin-bottom: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.order-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.order-item {
  display: flex;
  align-items: center;
  padding: 16px;
  gap: 20px;
}

.order-product {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 16px;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: contain;
  border-radius: 4px;
  background: #f5f5f5;
  padding: 4px;
}

.product-info {
  flex: 1;
}

.product-info h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin: 0;
}

.order-status {
  min-width: 100px;
  text-align: center;
}

.status-tag {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
  color: white;
}

.status-pending {
  background-color: #e6a23c;
}

.status-shipping {
  background-color: #409eff;
}

.status-receiving {
  background-color: #67c23a;
}

.status-completed {
  background-color: #909399;
}

.status-cancelled {
  background-color: #f56c6c;
}

.order-actions {
  min-width: 100px;
  text-align: center;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  padding: 0 20px;
}

:deep(.el-tabs__item.is-active) {
  font-weight: bold;
}
</style> 